var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var home=require("./routes/home");
var details=require("./routes/details");
var fs=require("fs");
var app = express();
var moment=require("moment");
var config=require("./config");
var logger=require("./utils/logger");
var multer = require('multer');
var bs_taobao=require("./routes/bs_taobao");//
var index=require("./routes/index");//文件上传

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

global.DB=require("./utils/DB").createDB();

//dev日志
morgan.token("utcDate",function(req,res){
  return moment(new Date).format("YYYY-MM-DD HH:mm:ss")
});

morgan.format("all",':remote-addr - :remote-user [:utcDate] ":method :url HTTP/:http-version" :status :res[content-length]');
if(config.env=="debug"){
  app.use(morgan('all'));
}else{
  app.use(morgan('all',
      {stream:fs.createWriteStream(path.join(__dirname, 'access.log'), {flags: 'a'})}
  ));
}

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'uploads')));

//挂载导航
// app.use('/', home);
// app.use('/', details);

app.all('*', function(req, res, next) {  
    res.header("Access-Control-Allow-Origin", "*");  
    res.header("Access-Control-Allow-Credentials","true");  
    res.header("Access-Control-Allow-Headers", "X-Requested-With,X-Custom-Header");  
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");  
    res.header("X-Powered-By",' 3.2.1')  
    res.header("Content-Type", "application/json;charset=utf-8");  
   
    next();  
});

app.use('/', bs_taobao);
app.use('/upload', index);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // render the error page
  res.status(err.status || 500);
  //写入错误信息
  if(config.env=="production"){
    logger.errorLog(err.stack);
  }
  res.render('error');
});

module.exports = app;
